package com.example.utils;

import cn.dev33.satoken.secure.BCrypt;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.example.entity.emp.SysUser;
import com.example.service.SysUserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 密码重置工具
 */
@Slf4j
@RestController
@RequestMapping("/reset")
@RequiredArgsConstructor
public class PasswordResetUtil {
    
    private final SysUserService userService;
    
    /**
     * 重置指定用户密码
     * @param username 用户名
     * @param plainPassword 明文密码
     * @return 重置结果
     */
    @GetMapping("/password/{username}/{plainPassword}")
    public String resetPassword(@PathVariable String username, @PathVariable String plainPassword) {
        try {
            // 加密密码
            String hashedPassword = BCrypt.hashpw(plainPassword);
            
            // 更新用户密码
            boolean updated = userService.update(
                new LambdaUpdateWrapper<SysUser>()
                    .eq(SysUser::getUsername, username)
                    .set(SysUser::getPassword, hashedPassword)
            );
            
            if (updated) {
                return "密码重置成功！用户: " + username + ", 新密码: " + plainPassword + ", 哈希值: " + hashedPassword;
            } else {
                return "密码重置失败，用户不存在: " + username;
            }
        } catch (Exception e) {
            log.error("密码重置异常", e);
            return "密码重置失败: " + e.getMessage();
        }
    }
    
    /**
     * 重置所有用户密码为123456
     */
    @GetMapping("/all")
    public String resetAllPasswords() {
        try {
            // 加密密码
            String hashedPassword = BCrypt.hashpw("123456");
            
            // 更新所有用户密码
            boolean updated = userService.update(
                new LambdaUpdateWrapper<SysUser>()
                    .set(SysUser::getPassword, hashedPassword)
            );
            
            return "所有用户密码重置成功！新密码: 123456, 哈希值: " + hashedPassword;
        } catch (Exception e) {
            log.error("密码重置异常", e);
            return "密码重置失败: " + e.getMessage();
        }
    }
} 